/*
*   id: 点击某个按钮显示上传提示框的按钮id
*   url: 上传文件调用的接口地址
*   callback: 上传成功后的回调
*   errorCallback: 上传失败后的回调
*   maxSize：上传文件的最大值，单位是M，不传的话默认是1M
*/
function imgupload(url,callback,errorCallback,maxSize) {
    this.url = url;
    this.callback = callback;
    this.errorCallback = errorCallback;
    this.multiple = !!!maxSize ? 1 : maxSize;
    this.maxsize = this.multiple*1024*1024;
    this.$self = $("#J_uploadModel");
    var that;
}

imgupload.prototype = {
    constructor:imgupload,
    isLock:true,
    browserCfg:{},
    maxsize:0,  // 单位是K (0.5*1024*1024 = 0.5M)
    allImgExt:".jpg|.jpeg|.gif|.png|",//全部图片格式类型 
    errMsg:'图片大小超过限制',
    tipStr:'上传文件格式为jpg、jpeg、gif、png',
    tipMsg:"您的浏览器暂不支持计算上传文件的大小,建议使用IE、FireFox、Chrome浏览器",
    $self:null,
    init:function(index) {
        that = this;
        if(that.multiple >=1 ) {
            that.$self.find(".uploadModel-th-tips").html(that.multiple + "M");
        }else {
            that.$self.find(".uploadModel-th-tips").html(that.multiple*1024 + "K");
        }
        
        $('.image-editor').cropit({
            exportZoom: 1,
            imageBackground: true,
            imageBackgroundBorderWidth: 20,
            imageState: {
                src: 'http://lorempixel.com/500/400/'
            }
        });
        that._createMask();
        that._bindEvent();
        that.checkBrowser();
    },
    //事件绑定
    _bindEvent:function() {
       that.$self.find(".close-uploadModel").on("click",that._closeModel);
       that.$self.find(".cropit-image-input").on("change",that._getFileParams);
       that.$self.find(".uploadModel-btn-sure").on("click",that._sureUpload);
       
       // 判断是否已经绑定了事件
       var json = $._data($('.choose-btn-area').get(0));
       var len = !!!json.events ? 0 : json.events.click.length;
       if(len < 1) {
           //选择图片
           that.$self.find(".choose-btn-area").on("click",function() {
                that.$self.find(".cropit-image-input").click();
           });
       }
       // //重新选择
       that.$self.find(".uploadModel-btn-rechoose").on("click",function() {
            that.$self.find(".cropit-image-input").click();
       });
    },
    //添加遮罩
    _createMask:function() {
        var obj = $("#upload-mask");
        if(!obj.length) {
            var width = $(window).width();
            var height = $(window).height();
            $("body").append('<div id="upload-mask"></div>');
        }
    },
    // 阻止鼠标滚动默认行为
    MouseWheelHandler:function(evt) {
        evt.preventDefault();
        return false;
    },
    //检查浏览器
    checkBrowser:function() {
        var ua = window.navigator.userAgent;  
        if (ua.indexOf("MSIE")>=1){  
            that.browserCfg.ie = true;  
        }else if(ua.indexOf("Firefox")>=1){  
            that.browserCfg.firefox = true;  
        }else if(ua.indexOf("Chrome")>=1){  
            that.browserCfg.chrome = true;  
        }
    },
    _getFileParams:function(evt) {

        var MyTest = document.getElementById("cropit-image-input").files[0];
        var reader = new FileReader();
        reader.readAsDataURL(MyTest);
        reader.onload = function(theFile) {
        　 var image = new Image();
               image.src = theFile.target.result;
               image.onload = function() {
               if(this.width < 300 || this.height < 300) {
                    $(".image-editor").show();
                    that.$self.find(".choose-btn-area").hide();
                    that.$self.find(".uploadModel-btn-rechoose").css("display","block");
                    that.$self.find(".errorMask").show().find(".upload-error-tips").html("请上传300*300以上的图片");
                    return false;
               }
                that._checkfile(evt);
           };
        };
    },
    //检查文件大小
    _checkfile:function(evt) {
        try{
            var obj_file = document.getElementById("cropit-image-input");
            var filesize = 0;
            var src = $.trim(obj_file.value);
            if(src == ""){
                that.isLock = true;
                return false;
            }
            $(".image-editor").show();
            that.$self.find(".choose-btn-area").hide();
            var FileExt = src.substr(src.lastIndexOf(".")).toLowerCase();
            if(that.allImgExt.indexOf(FileExt+"|") == -1 ) {
                that.$self.find(".errorMask").show().find(".upload-error-tips").html(that.tipStr);
                return false;
            }
            
            if(that.browserCfg.firefox || that.browserCfg.chrome ){
                filesize = obj_file.files[0].size;  //如果用jquery是obj_file[0]
            }else if(that.browserCfg.ie){
                var obj_img = document.getElementById('tempimg');
                obj_img.dynsrc=obj_file.value;
                filesize = obj_img.fileSize;
            }else{
                that.isLock = true;
                that.$self.find(".errorMask").show().find(".upload-error-tips").html(that.tipMsg);
            }

            if(filesize==-1){
                that.isLock = true;
                that.$self.find(".errorMask").show().find(".upload-error-tips").html(that.tipMsg);
            }else if(filesize>that.maxsize){
                that.isLock = true;
                that.$self.find(".uploadModel-btn-rechoose").css("display","block");
                that.$self.find(".errorMask").show().find(".upload-error-tips").html(that.errMsg);
            }else{
                that.isLock = false;
                that.$self.find(".group-range").show();
                that.$self.find(".uploadModel-btn-rechoose").hide();
                that.$self.find(".uploadModel-btn-sure").css("display","block");
                var timer = setTimeout(function() {
                    that.$self.find(".errorMask").hide();
                    clearTimeout(timer);
                }, 500);
            }
            
            return false;

        }catch(e){
            alert(e);
        }
    },
    //显示上传框
    _showModel:function() {
        that.isLock = true;
        that.$self.css({
            top:'50%',
        });
        $("#upload-mask").show();
        $("body").css("overflow","hidden");
        that.$self.find(".choose-btn-area").show();
        $(document).on("mousewheel DOMMouseScroll",that.MouseWheelHandler);
    },
    //关闭上传框
    _closeModel:function() {
        that.$self.css({
            top:'-100%',
        });
        $("#upload-mask").hide();
        $("#cropit-image-input").val('');
        $("body").css("overflow","initial");
        that.$self.find(".loader-wrap").hide();
        that.$self.find(".cropit-preview-image").attr("src","");
        that.$self.find(".cropit-preview-background").attr("src","");
        that.$self.find(".group-range,.uploadModel-btn,.image-editor,.errorMask").hide();
        $(document).off("mousewheel DOMMouseScroll",that.MouseWheelHandler);
    },
    // 确定上传
    _sureUpload:function() {
        if(that.isLock) {
            return false;
        }
        that.$self.find(".loader-wrap").show();
        that.isLock = true;
        var imageData = $('.image-editor').cropit('export');
        var data = {"data":imageData};
        that._request_data(that.url,data,that._sureUploadCallBack,that._sureUploadErrorCallBack);
    },
    // 成功callback
    _sureUploadCallBack:function(ret) {
        that.isLock = false;
        that.$self.find(".loader-wrap").hide();
        that._closeModel();
        that.callback && that.callback(ret);
    },
    // 失败callback
    _sureUploadErrorCallBack:function(err) {
        that.isLock = false;
        that._closeModel();
        that.$self.find(".loader-wrap").hide();
        that.errorCallback && that.errorCallback(err);
    },
    _request_data:function(url,data,callback,errorCallback) {
        $.ajax({
            type:"post",
            url:url,
            dataType:"json",
            data:data,
            success:function(ret) {
                callback && callback(ret);
            },
            error:function(err) {
                errorCallback && errorCallback(err);
            }
        })
    }
}